<?php
	
	/**
	 * This class will handle all the async json requests we get from the server.
	 */
	class Ajaj{
		public function load(){
			if(!data('fb')->userIsLoggedIn){
				$this->app->throwError('page_not_exists');
			}
		}
		
		/**
		 * Gets the privacy settings (used in the header)
		 */
		public function getUserPrivacySettings(){
			$users = new Users();
			echo json_encode($users->read(data('fb')->user, array('isPublic')));
		}
		
		/**
		 * Sets the privacy settings (used in the header)
		 */
		public function updatePrivacySettings(){
			$users = new Users();
			$users->update(data('fb')->user, array('isPublic'), array($_POST['isPublic']));
		}
		
		/**
		 * Search function (used in the header)
		 */
		public function search(){
			$users = new Users();
			
			if(isset($_POST['keyword']) && strlen($_POST['keyword']) >= 2){
				$searchResults = null;
				$searchResults['friends'] = $users->searchFriends(data('fb')->user, $_POST['keyword']);
				$searchResults['cache'] = $users->searchCache(data('fb')->user, $_POST['keyword']);
				
				echo json_encode($searchResults);
			}
		}
		
		/**
		 * This function searches a location (used in create activity)
		 */
		public function searchLocation(){
			if(isset($_POST['keyword']) && strlen($_POST['keyword']) >= 2){
				$users = new Users();
				$locations = new Locations();
				
				$searchResults = null;
				$searchResults['cities'] = null;
				$searchResults['companies'] = $locations->searchCompany($_POST['keyword']);
				$searchResults['friends'] = $users->searchFriends(data('fb')->user, $_POST['keyword']);
				
				if($_POST['country'] && strlen($_POST['country']) >= 2){
					$searchResults['cities'] = $locations->readCityFromCountry($_POST['keyword'], $_POST['country']);
				}
				
				echo json_encode($searchResults);
			}
		}
		
		/**
		 * This function searches in the friends of the user (used in all friend selectors in functions.js)
		 */
		public function searchFriends(){
			if($_POST['keyword'] && strlen($_POST['keyword']) >= 2){
				$users = new Users();
				echo json_encode($users->searchFriends(data('fb')->user, $_POST['keyword']));
			}
		}

		/**
		 * Searches tags, used in create activity.
		 */
		public function searchTags(){
			if($_POST['keyword'] && strlen($_POST['keyword']) >= 2){
				$activities = new Activities();
				echo json_encode($activities->searchTag($_POST['keyword']));
			}
		}
		
		/**
		 * Creates a new activity, used in create activity.
		 */
		public function createActivity(){
			if(isset($_POST['date']) && 
			strlen($_POST['date']) === 10 &&
			isset($_POST['time']) &&
			isset($_POST['endDate']) &&
			isset($_POST['endTime']) &&
			isset($_POST['destId']) &&
			strlen($_POST['destId']) > 0 &&
			isset($_POST['destType']) &&
			strlen($_POST['destType']) > 0 &&
			isset($_POST['withWho']) &&
			isset($_POST['tagText']) && 
			isset($_POST['tagId'])){
				
				$users = new Users();
				
				// Tags should only be max 10 characters, don't even
				// bother to send a message back since the client is hacking js
				// at this point.
				if(strlen($_POST['tagText'] > 10) || !$users->isAllowedToCreateActivity(data('fb')->user)){
					return null;
				}
				
				// Cast everything to lowercase to start.
				foreach($_POST as $postKey => &$v){
					$v = strtolower($v);
				}
				
				// If the user did put in an end time but not an end date... the end date would be the same as the $_POST['date'].
				if($_POST['endTime'] !== '' && $_POST['endDate'] === ''){
					$_POST['endDate'] = $_POST['date'];
				}
				
				// Cast the date to correct format.
				$dateExplode = explode('-', $_POST['date']);
				$day = $dateExplode[0];
				$month = $dateExplode[1];
				$year = $dateExplode[2];
				$hour = 0;
				$minute = 0;
				$timeString = null;
				
				// If the user submitted a time...
				if(strlen($_POST['time']) === 5){
					$timeExplode = explode(':', $_POST['time']);
					$hour = $timeExplode[0];
					$minute = $timeExplode[1];
					$timeString = $timeExplode[0] . ':' . $timeExplode[1] . ':' . '00';
				}
				
				// Now put it into a date object, we can now calculate all the 
				// required calculations.
				$date = new Date($year, $month, $day, $hour, $minute);
				
				// If the date NOT in the future...
				if(!$date->isInFuture('-1 week')){
					echo json_encode(array(
						'error' => 'dateIsInPast'
					));
					
					exit;
				}
				
				$eDateString = null;
				$eTimeString = null;

				// If the user submitted an end date...
				if(strlen($_POST['endDate']) === 10){
					$eDateExplode = explode('-', $_POST['endDate']);
					$eDay = $eDateExplode[0];
					$eMonth = $eDateExplode[1];
					$eYear = $eDateExplode[2];
					$eHour = 0;
					$eMinute = 0;

					// If the user submitted an end time...
					if(strlen($_POST['endTime']) === 5){
						$eTimeExplode = explode(':', $_POST['endTime']);
						$eHour = $eTimeExplode[0];
						$eMinute = $eTimeExplode[1];
					}

					// Now put this one also in date object.
					$eDate = new Date($eYear, $eMonth, $eDay, $eHour, $eMinute);

					// Lets check whether the end date is actualy PAST the start date.
					if(!$eDate->isAfter($date)){
						echo json_encode(array(
							'error' => 'eDateWasBeforeDate'
						));

						exit;
					}

					// Fill in the end date and end time strings else
					// we don't have anything to pass through the database.
					$eDateString = $eDate->toMysqlDate();
					$eTimeString = $eDate->toMysqlTime();
				}
				
				$activities = new Activities();
				
				// Now check the tags.
				$tagId = $_POST['tagId'];
				
				// If the user did not pick a tag..
				if(strlen($_POST['tagText']) > 0){
					
					// Check if the input was only alphabet.
					if(!ctype_alpha($_POST['tagText'])){
						echo json_encode(array(
							'error' => 'tagSpecialChars'
						));
						
						exit;
					}
					
					$foundTag = $activities->readTagByName($_POST['tagText']);
					
					// If the tag was not found, we have to create it.
					if($foundTag === null){
						$tagId = $activities->createTag(data('fb')->user, $_POST['tagText']);
						
					// Else the tag was found, we have to set the id of the tag.
					} else {
						$tagId = $foundTag['id'];
					}
				}
				
				// With who...
				$withWho = array();
				
				if(strlen($_POST['withWho']) > 0){
					$withWho = explode(',', $_POST['withWho']);
				}
				
				// Create the activity.
				$activityId = $activities->create(data('fb')->user, $date->toMysqlDate(), $timeString, $eDateString, $eTimeString, $_POST['destType'], $_POST['destId'], $tagId);
				
				// Bind the with who users, if they are friend with the user.
				if(count($withWho) > 0){ 
					foreach($withWho as $friendUser){
						if($users->isFriendWith(data('fb')->user, $friendUser)){
							$activities->bindUserToActivity($activityId, $friendUser, 0);
						}
					}
				}
				
				// Lets not forget to add yourself to the activity.
				$activities->bindUserToActivity($activityId, data('fb')->user, 1);
				
				// Lets add the object to the cache of the user. Only if is a city or company.
				if($_POST['destType'] === '3' || $_POST['destType'] === '1'){
					$users->createSearchCacheObject(data('fb')->user, $_POST['destId'], $_POST['destType']);
				}
				
				echo json_encode(array('error' => 'ok'));
			}
		}
		
		/**
		 * Reads the stream of the user homepage.
		 */
		public function readHomepageStream(){
			if(isset($_POST['filter']) && isset($_POST['limit'])){
				$date = null;
				
				if($_POST['filter'] === 'date' && isset($_POST['date'])){
					$fixedDate = explode('-', $_POST['date']);
					$date = $fixedDate[2] . '-' . $fixedDate[1] . '-' . $fixedDate[0];
				}
				
				$activities = new Activities();
				echo json_encode($activities->readHomepageStream(data('fb')->user, $_POST['filter'], $_POST['limit'], $date));
			}
		}
		
		/**
		 * Read company stream
		 */
		public function readCompanyStream(){
			if(isset($_POST['filter']) &&
			isset($_POST['limit']) &&
			isset($_POST['displayMales']) &&
			isset($_POST['displayFemales']) &&
			isset($_POST['displayFriendsOnly']) &&
			isset($_POST['displaySinglesOnly']) &&
			isset($_POST['companyId'])){
				$date = null;
				
				if($_POST['filter'] === 'date' && isset($_POST['date'])){
					$fixedDate = explode('-', $_POST['date']);
					$date = $fixedDate[2] . '-' . $fixedDate[1] . '-' . $fixedDate[0];
				}
				
				$activities = new Activities();
				echo json_encode($activities->readCompanyStream(data('fb')->user, $_POST['companyId'], $_POST['filter'], $_POST['limit'], $_POST['displayMales'], $_POST['displayFemales'], $_POST['displayFriendsOnly'], $_POST['displaySinglesOnly'], $date));
			}
		}
		
		/**
		 * Read notifications of the user.
		 */
		public function readNotifications(){
			$users = new Users();
			echo json_encode($users->readNotifications(data('fb')->user));
		}
		
		/**
		 * Update a notification of the user.
		 */
		public function updateNotification(){
			if(isset($_POST['id']) && isset($_POST['decision'])){
				$users = new Users();
				
				// Lets first check whether the notification actually belongs to the user.
				if($users->notificationBelongsToUser(data('fb')->user, $_POST['id'])){
					$users->updateNotification($_POST['id'], $_POST['decision']);
				}
			}
		}
		
		/**
		 * Do extended search.
		 */
		public function extendedSearch(){
			if(isset($_POST['keyword']) && strlen($_POST['keyword']) >= 4){
				$users = new Users();
				echo json_encode($users->extendedSearch(data('fb')->user, $_POST['keyword'], 'nl'));
			}
		}
		
		/**
		 * Read user stream.
		 */
		public function readUserStream(){
			if(isset($_POST['filter']) && isset($_POST['userId']) && isset($_POST['date']) && isset($_POST['limit'])){
				$users = new Users();
				
				// If the user is allowed to read the stream of the user.
				if($users->isFriendWith(data('fb')->user, $_POST['userId']) || $users->read($_POST['userId'], array('isPublic')) === '1'){
					$activities = new Activities();
					$date = null;
					
					if($_POST['filter'] === 'date' && isset($_POST['date'])){
						$fixedDate = explode('-', $_POST['date']);
						$date = $fixedDate[2] . '-' . $fixedDate[1] . '-' . $fixedDate[0];
					}
					
					echo json_encode($activities->readUserStream($_POST['userId'], $_POST['filter'], $_POST['limit'], $date));
				}
			}
		}
		

//		public function getStream(){
//			if(isset($_POST['page']) && strlen($_POST['page']) >= 2 && isset($_POST['activeFilter']) && strlen($_POST['activeFilter']) >= 2 && isset($_POST['limit']) && $_POST['limit'] < 350){
//				$results = null;
//				$date = null;
//				$extraFilters = null;
//				
//				if(isset($_POST['extraFilters'])){
//					$extraFilters = $_POST['extraFilters'];
//				}
//
//				if($_POST['activeFilter'] === 'date'){
//					$fixedDate = explode('-', $_POST['parameters']['date']);
//					$date = $fixedDate[2] . '-' . $fixedDate[1] . '-' . $fixedDate[0];
//				}
//
//				if($_POST['page'] === 'home'){
//					$results = $this->app->model('users')->getActivities($this->fb->user, $_POST['activeFilter'], $_POST['limit'], null, null, $date, $extraFilters);
//					
//				} else if($_POST['page'] === 'userProfile' && isset($_POST['parameters']['objId']) && strlen($_POST['parameters']['objId']) > 2){
//					$results = $this->app->model('users')->getActivities($this->fb->user, $_POST['activeFilter'], $_POST['limit'], 2, $_POST['parameters']['objId'], $date, $extraFilters);
//					
//				} else if($_POST['page'] === 'companyProfile' && isset($_POST['parameters']['objId']) && strlen($_POST['parameters']['objId']) > 2){
//					$results = $this->app->model('users')->getActivities($this->fb->user, $_POST['activeFilter'], $_POST['limit'], 1, $_POST['parameters']['objId'], $date, $extraFilters);
//				}
//				
//				if(isset($results['activities'])){
//					foreach($results['activities'] as &$activity){
//						$this->processActivity(&$activity);
//					}
//				}
//				
//				echo json_encode($results);
//			}
//		}
//		

//		
//		public function userCreateLocation(){
//			if(isset($_POST['name']) && isset($_POST['city']) && strlen($_POST['name']) > 2 && strlen($_POST['city']) > 2){
//				if($this->app->model('users')->userCreatedLocationCountToday($this->fb->user) < 5){
//					$city = $this->app->model('locations')->getCity($_POST['city']);
//					$this->app->model('locations')->userCreateLocation(strtolower($_POST['name']), $this->fb->user, strtolower($city['name']));
//				} else {
//					echo json_encode(array('error' => 'limitExceeded'));
//				}
//			}
//		}
//		
//		public function searchCity(){ 
//			if($_POST['keyword'] && strlen($_POST['keyword']) >= 2){
//				if(!isset($_POST['country'])){
//					echo json_encode($this->app->model('locations')->searchCity($_POST['keyword']));
//				} else {
//					if(strlen($_POST['country']) >= 2){
//						$country = $this->app->model('locations')->getCountry($_POST['country']);
//						
//						if($country){
//							echo json_encode($this->app->model('locations')->searchCityInCountry($_POST['keyword'], $country['iso']));
//						}
//					}
//				}
//			}
//		}
//		
//		public function locationSearch(){
//			if(isset($_POST['keyword']) && isset($_POST['isTrip']) && isset($_POST['place'])){
//				$searchResults = null;
//				$searchResults['cities'] = '';
//				$searchResults['companies'] = '';
//				$searchResults['friends'] = '';
//				
//				if($_POST['isTrip'] !== 'true'){
//					$searchResults['friends'] = $this->app->model('users')->searchUserFriends($this->fb->user, $_POST['keyword']);
//
//					if(strlen($_POST['place']) > 2){
//						$searchResults['companies'] = $this->app->model('locations')->searchCompanyInCity($_POST['keyword'], $_POST['place']);
//					} else {
//						$searchResults['companies'] = $this->app->model('locations')->searchCompany($_POST['keyword']);
//					}
//				} else {
//					$searchResults['cities'] = $this->app->model('locations')->searchCity($_POST['place']);
//				}
//				
//				echo json_encode($searchResults);
//			}
//		}
//		
//		public function setIsPublic(){
//			if($_POST['isPublic'] === 'false'){
//				$_POST['isPublic'] = false;
//			} else if($_POST['isPublic'] === 'true'){
//				$_POST['isPublic'] = true;
//			}
//		
//			$this->app->model('users')->setUserIsPublic($this->fb->user, $_POST['isPublic']);
//		}
//		
//		public function getProfile(){
//			echo json_encode(array(
//				'isPublic' => $this->app->model('users')->isUserPublic($this->fb->user),
//				'locationsCreatedToday' => $this->app->model('users')->userCreatedLocationCountToday($this->fb->user),
//				'locationsCreatedTotal' => $this->app->model('users')->userCreatedLocationCountTotal($this->fb->user)
//			));
//		}
	}
		
// File end.